import axios from 'axios'
import { Toast } from 'vant'
import { removeLocal, getLocal } from '@/utils/local.js'
import store from '@/store'
import router from '@/router'

const _fetch = axios.create({
  baseURL: process.env.VUE_APP_URL
})

// 添加请求拦截器
_fetch.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // console.log(config)
    if (config.needtoken) {
      config.headers.authorization = `Bearer ${getLocal('token')}`
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
_fetch.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    if (response.data.code === 200) {
      return response
    } else {
      if (response.data.code === 401 || response.data.code === 403) {
        removeLocal('token')
        Toast.fail(response.data.message)
        // console.log(response.data.message)
        store.commit('setIsLogin', false)
        router.push('/login')
        return Promise.reject(new Error(response.data.message))
      } else {
        Toast.fail(response.data.message)
        return Promise.reject(new Error(response.data.message))
      }
    }
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

export default _fetch
